/*
 * @Author: chichiksky
 * @Date: 2022-03-24 21:57:06
 * @LastEditTime: 2022-04-02 11:06:39
 * @LastEditors: your name
 * @Description: 客户端教师或学生个人信息页面
 * @FilePath: \web\src\router\class\classChild\userInfo\index.jsx
 */

import "./index.css";
import React, { useState } from "react";
import { Card, Descriptions, Form, Input, Button, message } from "antd";
import request from "../../../../network/index";
import Cookie from "../../../../assets/common/cookie";

const UserInfo = () => {
  const [activeTabKey1, setActiveTabKey1] = useState("tab1");

  // 从 cookie 中获取个人信息
  const userInfo = Cookie.get("userInfo")
    ? JSON.parse(Cookie.get("userInfo"))
    : "";
  console.log("userInfo", userInfo);

  // 基本信息相关设置
  const info = (
    <Descriptions column={2}>
      <Descriptions.Item label="姓名">{userInfo.username}</Descriptions.Item>
      <Descriptions.Item label="学号/工号">{userInfo.id}</Descriptions.Item>
      <Descriptions.Item label="学院">{userInfo.academy}</Descriptions.Item>
      {Number(userInfo.type) === 3 ? (
        <Descriptions.Item label="专业">{userInfo.major}</Descriptions.Item>
      ) : (
        ""
      )}
      {Number(userInfo.type) === 3 ? (
        <Descriptions.Item label="班级">{userInfo._class}</Descriptions.Item>
      ) : (
        ""
      )}
    </Descriptions>
  );

  // 修改密码相关设置
  const [form] = Form.useForm();

  const onFinish = (values) => {
    editPassword(values);
    form.resetFields();
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  // 修改密码接口调用
  const editPassword = async (values) => {
    const url = Number(userInfo.type) === 2 ? "/teacher" : "/student";
    const result = await request.put(url, {
      id: userInfo._id,
      password: values.password,
      init: values.init,
    });
    result && message.success("修改成功!", 1.5);
  };
  const passInfo = (
    <Form
      className="passForm"
      name="basic"
      form={form}
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 6 }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="原密码"
        name="init"
        rules={[{ required: true, message: "请输入原密码!" }]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item
        label="新密码"
        name="password"
        hasFeedback
        rules={[
          { required: true, message: "请输入新密码!" },
          () => ({
            validator(_, value) {
              if (value.match(/^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[._@#$])[A-Za-z0-9._@#$]{8,16}$/)) {
                return Promise.resolve();
              }
              return Promise.reject(new Error("新密码应符合规则!"));
            },
          }),
        ]}
      >
        <Input.Password />
      </Form.Item>
      <span className="ant-form-text">
        密码由8-16位字符（字母和数字及._@#$特殊字符）组成
      </span>
      <Form.Item
        label="确认新密码"
        name="new"
        dependencies={["password"]}
        hasFeedback
        rules={[
          {
            required: true,
            message: "请再次输入新密码!",
          },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue("password") === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error("您输入的两个密码不匹配！"));
            },
          }),
        ]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item wrapperCol={{ offset: 6, span: 8 }}>
        <Button type="primary" htmlType="submit">
          提交
        </Button>
      </Form.Item>
    </Form>
  );

  // 主页面 card设置
  const tabList = [
    {
      key: "tab1",
      tab: "基本信息",
    },
    {
      key: "tab2",
      tab: "密码设置",
    },
  ];

  const contentList = {
    tab1: info,
    tab2: passInfo,
  };

  const onTab1Change = (key) => {
    setActiveTabKey1(key);
  };

  return (
    <Card
      style={{ width: "100%", height: "100%" }}
      tabList={tabList}
      activeTabKey={activeTabKey1}
      onTabChange={(key) => {
        onTab1Change(key);
      }}
    >
      {contentList[activeTabKey1]}
    </Card>
  );
};
export default UserInfo;
